package com.action.gulimall.auth.controller;

import com.action.common.constant.AuthServerConstant;
import com.action.common.exception.BizCodeEnum;
import com.action.common.utils.R;
import com.action.common.vo.MemberResponseVo;
import com.action.gulimall.auth.feign.MemberFeignService;
import com.action.gulimall.auth.feign.ThridPartyFeginService;
import com.action.gulimall.auth.vo.UserLoginVo;
import com.action.gulimall.auth.vo.UserRegisterVo;
import com.alibaba.fastjson.TypeReference;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author sl shilun217@qq.com
 * @Deacription TODO
 * @date 2021/06/28/19:42
 **/
@Controller
public class LoginController {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Autowired(required = false)
    ThridPartyFeginService thridPartyFeginService;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @RequestMapping("/sms/sendCode")
    public R sendSms(@RequestParam(value="phone") String phone){
        String smsCodeKey=AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;

        String codeStr = stringRedisTemplate.opsForValue().get(smsCodeKey);
        if(!StringUtils.isEmpty(codeStr)){
            String[] split = codeStr.split("_");
            //同一个phone 60s内只能发一次
            if(System.currentTimeMillis()-Long.valueOf(split[1])<60){
                return R.error(BizCodeEnum.SMS_CODE_EXCEPTION.getCode(), BizCodeEnum.SMS_CODE_EXCEPTION.getMessage());
            }
        }
        String code = String.valueOf((int)((Math.random() * 9 + 1) * 100000));
        codeStr = code+"_"+System.currentTimeMillis();
        stringRedisTemplate.opsForValue().set(smsCodeKey, codeStr, 5, TimeUnit.MINUTES);
        //调用第三方组件发送短信验证码
        thridPartyFeginService.sendSmsCode(phone, code);
        return R.ok();
    }

    @PostMapping(value = "/register")
    public String register(@Valid UserRegisterVo userRegisterVo,
                           BindingResult bindingResult, RedirectAttributes redirectAttributes){
        if(bindingResult.getErrorCount()>0){
            Map<String, String> errors = bindingResult.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            redirectAttributes.addFlashAttribute("errors", errors);
            //效验出错回到注册页面
            return "redirect:http://auth.gulimall.com/reg.html";
        }
        //校验验证码
        String smsCodeKey=AuthServerConstant.SMS_CODE_CACHE_PREFIX + userRegisterVo.getPhone();
        String codeStr = stringRedisTemplate.opsForValue().get(smsCodeKey);
        if(!StringUtils.isEmpty(codeStr)) {
            String[] split = codeStr.split("_");
            if(split[0].equals(userRegisterVo.getCode())){
                //删除令牌
                //进行真正的注册
                stringRedisTemplate.delete(smsCodeKey);
                R r = memberFeignService.register(userRegisterVo);
                if(r.getCode()!=0){
                    //调用失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getMsg());
                    redirectAttributes.addFlashAttribute("errors",errors);
                    return "redirect:http://auth.gulimall.com/reg.html";
                }
                return "redirect:http://auth.gulimall.com/login.html";
            }else{
                Map<String, String> errors = new HashMap<String,String>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                //效验出错回到注册页面
                return "redirect:http://auth.gulimall.com/reg.html";
            }
        }else{
            Map<String, String> errors = new HashMap<String,String>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            //效验出错回到注册页面
            return "redirect:http://auth.gulimall.com/reg.html";
        }
    }

    @GetMapping(value = "/login.html")
    public String loginPage(HttpSession session) {
        //从session先取出来用户的信息，判断用户是否已经登录过了
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        //如果用户没登录那就跳转到登录页面
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }
    }

    @PostMapping(value = "/login")
    public String login(UserLoginVo userLoginVo,HttpSession session,RedirectAttributes redirectAttributes){
        R login = memberFeignService.login(userLoginVo);
        if(login.getCode()!=0){
            //登录失败返回错误信息到重定向登录页面
            Map<String, String> errors = new HashMap<String,String>();
            errors.put("code", "用户密码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "login";
        }else{
            MemberResponseVo data = login.getData(new TypeReference<MemberResponseVo>() {}).get();
            //登录成功放入session
            session.setAttribute(AuthServerConstant.LOGIN_USER,data);
            return "redirect:http://gulimall.com";
        }
    }

    @GetMapping(value = "/loguot.html")
    public String logout(HttpServletRequest request) {
        request.getSession().removeAttribute(AuthServerConstant.LOGIN_USER);
        request.getSession().invalidate();
        return "redirect:http://gulimall.com";
    }
}
